//工具函数

const api = require('./api.js');
const util = require('./util.js');

//缓存中写入默认数据
function writeDefaultData(app) {
    let date = new Date().getDate();
    let firstOpen = wx.getStorageSync('firstOpen');
    console.log('firstOpen', firstOpen);
    if (!firstOpen) { //如果不存在firstOpen，则写入一个数据
        wx.setStorageSync('firstOpen', { 'date': date, 'DefaultTimes': 1, 'redPaperIsOpened': false });
        app.globalData.DefaultTimes = 1;
    } else {
        if (firstOpen.date != date) { //如果有firstOpen，看日期是不是当天，如果不是写入一个数据
            wx.setStorageSync('firstOpen', { 'date': date, 'DefaultTimes': 1, 'redPaperIsOpened': false });
            return;
        }
        //如果有firstOpen，而且是当天，则读取原来的数据
        app.globalData.DefaultTimes = firstOpen.DefaultTimes;
        app.globalData.redPaperIsOpened = firstOpen.redPaperIsOpened
    }
}

//获取formId
function saveFormId(e) {
    let that = this;
    let formIdList = [];
    let time = new Date().getTime();
    // console.log('表单数据', e);
    //获取缓存中的formId
    wx.getStorage({
        key: 'formId',
        success: function(res) {
            console.log('缓存中的formId', res.data)
            formIdList = res.data || [];
        },
        fail: function(err) {
            console.log('缓存中没找到formId', err)
        },
        complete: function() {
            formIdList.push({
                formId: e.detail.formId,
                currentTime: Math.floor(time / 1000),
                expireTime: Math.floor(time / 1000) + 604800
            });
            wx.setStorage({
                key: "formId",
                data: formIdList
            })
        }
    })
}

//发送formId
function sendFormId(app) {
    let that = this;

    let openId = app.globalData.openId;
    let formIds = wx.getStorageSync('formId');

    if (!openId || !formIds) {
        return
    }

    api.methodSendFormId({
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        dataDic: {
            openId: openId,
            formIds: JSON.stringify(formIds)
        },
        success: function(res) {
            console.log('发送formid接口调用成功', res)

            if (res.data.code === 0) {
                //清除缓存中的formid值
                wx.removeStorage({
                    key: 'formId',
                    success: function(res) {
                        console.log('清理formId成功', res.data);
                        console.log('缓存中的formId', wx.getStorageSync('formId'))
                    },
                    fail: function(err) {
                        console.log('清理formId失败', err)
                    }
                })
            }
        },
        fail: function(err) {
            console.log('发送formId接口调用失败', err)
        }
    })
}

//判断微信sdk版本
function judgeSDKVersion(v) {
    if (v < 160) {
        wx.showModal({
            title: '提示',
            content: '当前微信版本过低，部分功能可能无法使用，建议升级到最新微信版本后重试。',
            showCancel: false,
            success: function(res) {
                if (res.confirm) {
                    return;
                }
            }
        })
        return;
    }
}
//获取token
function getToken(self) {
    // let address = 'http://ies.acadsoc.com.cn/ECI/WeChatSmallProgram/WeChat_Base.ashx';
    let address = 'http://192.168.74.98:8085/ECI/WeChatSmallProgram/WeChat_Base.ashx';
    let AppKey = '049BD15C6FC04BD80808A601DC46E50515CBEEA33FB29AB4';
    let appid = 'wx820493357a58f254';
    let secret = '5a6ec00b69f935b4453934a73e5de1c2';
    let url = `${address}?AppKey=${AppKey}&appid=${appid}&secret=${secret}&action=GetWechatToken`;
    wx.request({
        url: url,
        data: {},
        header: {
            'content-type': 'application/json' // 默认值
        },
        method: 'GET',
        success: function(res) {
            console.log('获取token请求成功', res)
            self.globalData.access_token = res.data.data.access_token;
        },
        fail: function(err) {
            console.log('获取token请求错误', err)
        },
        complete: function() {
            // console.log(self.globalData.access_token)
        }
    })

}
//绘制倒计时效果
function countDown(params, RemainingTime, scale, cb) {
    console.log('播放倒计时效果');
    let ctx_gray = wx.createCanvasContext('canvas-gray');

    let radius = 25

    //保证小屏幕能够完全显示出来
    if (scale < 0.9) {
        radius = 19
    }

    //画灰色的圆弧
    ctx_gray.setLineWidth(10);
    ctx_gray.arc(33, 35, radius, -0.5 * Math.PI, 1.5 * Math.PI)
    ctx_gray.setStrokeStyle('#dcdcdc');
    ctx_gray.stroke();
    ctx_gray.draw(true);

    let ctx_red = wx.createCanvasContext('canvas-red');
    let time = RemainingTime * 1000;
    let space = 50; //时间间隔，毫秒
    // let step = 2 * Math.PI * space * 0.32 / time; //移动步长
    // let bili = 20 * time / 1000;
    let step = space * 2 * Math.PI / time;
    let totalTime = 0; //花费的总时间
    let totalStep = 0; //走过的总步长

    let timer_daojishi = setInterval(function() {
        totalStep += step;
        totalTime += space;
        ctx_red.setLineWidth(10);
        ctx_red.setLineCap('round');
        drawcircle(ctx_red, totalStep, radius);
        if (totalTime >= time) {
            clearInterval(timer_daojishi);
            typeof cb == 'function' && cb();
            //倒计时结束清除画布
            ctx_gray.clearRect(0, 0, 140, 140);
            ctx_gray.draw(true);
            ctx_red.clearRect(0, 0, 140, 140);
            ctx_red.draw(true);
            return;
        }
    }, space)

    //画弧函数
    function drawcircle(ctx, step, radius) {
        ctx.arc(33, 35, radius, -0.5 * Math.PI, -0.5 * Math.PI + step);
        ctx.setStrokeStyle('#3DBF8F');
        ctx.stroke();
        ctx.draw(true);
    }
}

//获取小程序码
function getWxCode(obj, resolve, reject) {
    let that = this;
    let data = {
        scene: obj.scene,
        path: obj.page || 'pages/tabBarPackage/index/index',
        width: obj.width || 430,
        auto_color: obj.auto_color || false,
        line_color: obj.line_color || JSON.stringify({ "r": "0", "g": "0", "b": "0" })
    }
    console.log('获取小程序码data', data)
    api.methodGetWxaCode({
        method: 'POST',
        dataDic: data,
        contentType: 'application/x-www-form-urlencoded',
        success: (res) => {
            if (res.data.data.indexOf('http') == -1) {
                console.log('获取小程序码失败', res.data.data);
                typeof reject == 'function' && reject(res);
            } else {
                console.log('获取小程序码成功', res);
                typeof resolve == 'function' && resolve(res);
            }
        },
        fail: (err) => {
            console.log('获取小程序码失败', err);
            typeof reject == 'function' && reject(err);
        }
    })
}

function getWxCode_A(obj, resolve, reject) {
    let that = this;
    let data = {
        path: obj.page || 'pages/tabBarPackage/index/index',
        width: obj.width || 430,
        auto_color: obj.auto_color || false,
        line_color: obj.line_color || JSON.stringify({ "r": "0", "g": "0", "b": "0" }),
        is_hyaline: obj.is_hyaline || false
    }
    console.log('获取小程序码a data', data)
    api.methodGetWxaCode_a({
        method: 'POST',
        dataDic: data,
        contentType: 'application/x-www-form-urlencoded',
        responseType: 'stream',
        success: (res) => {
            console.log('获取小程序码成功', res);
            // if (res.data.data.indexOf('http') == -1) {
            //     console.log('获取小程序码失败', res.data.data);
            //     typeof reject == 'function' && reject(res);
            // } else {

            //     typeof resolve == 'function' && resolve(res);
            // }
        },
        fail: (err) => {
            console.log('获取小程序码失败', err);
            typeof reject == 'function' && reject(err);
        }
    })
}

//获取练习次数
function getPracticeTimes(params, cb) {
    console.log('获取练习次数');

    api.methodGetChallengeCount({
        dataDic: {
            OpenId: params.OpenId,
            UID: params.UID
        },
        complete: function(res) {
            console.log('获取练习次数完成', res);
            typeof cb == 'function' && cb(res);
        }
    })
}

//增加练习次数
function addPracticeTimes(query, that) {
    // let query = options.query;
    console.log('url中的参数', query);
    let QID = query.QID;
    let dataDic = {
        openid: that.globalData.openId,
        ShareOpenId: query.shareOpenId,
        UID: query.shareUID,
    };
    //给分享人增加一次练习次数AccountsTimes
    api.methodAddPracticeNumbers({
        dataDic: dataDic,
        complete: function(res) {
            console.log('app.js中增加练习次数请求完成', res);
            if (res.data.code == 0) {
                console.log('增加练习次数成功');
            }
        }
    });
}

//计时时间转为时间格式
function timeFormat(param) {
    let M = util.formatNumber(Math.floor(param / (60)) % 60);
    let S = util.formatNumber(Math.floor(param) % 60);
    let text = M + ":" + S;
    return text;
}

//页面跳转
function getoPage(pathName, action, delta) {
    switch (action) {
        case 'redi':
            wx.redirectTo({
                url: `/${pathName}`,
                success: function(res) {
                    // success
                }
            })
            break;
        case 'tab':
            wx.switchTab({
                url: `/${pathName}`,
                success: function(res) {
                    // success
                }
            })
            break;
        case 'back':
            wx.navigateBack({
                delta: delta || 1
            })
            break;
        case "reL":
            wx.reLaunch({
                url: `/${pathName}`,
                success: function(res) {
                    // success
                }
            })
            break;
        default:
            wx.navigateTo({
                url: `/${pathName}`,
                success: function(res) {
                    // success
                }
            })
            break;
    }
}

module.exports = {
    writeDefaultData,
    saveFormId,
    sendFormId,
    judgeSDKVersion,
    getToken,
    countDown,
    getWxCode,
    getWxCode_A,
    getPracticeTimes,
    addPracticeTimes,
    timeFormat,
    getoPage
}